#include"comm.h"

	union semun {
         int  val;    /* Value for SETVAL */
  		 struct semid_ds *buf;    /* Buffer for IPC_STAT, IPC_SET */
    	 unsigned short  *array;  /* Array for GETALL, SETALL */
		 struct seminfo  *__buf;  /* Buffer for IPC_INFO*/
};

static int comm_get_sem(int nsems,int flag)
{
	key_t sem_key=ftok(_PATH_,_PROJ_ID_);
	if(sem_key<0)
	{
		perror("ftok");
	}
	int sem_id=semget(sem_key,nsems,flag);
	if(sem_id<0)
	{
		perror("semget");
	}
	return sem_id;
}
int creat_sem(int nsems)
{
	umask(0);
	return comm_get_sem(nsems,IPC_CREAT|IPC_EXCL|0666);
}
int get_sem(int nsems)
{
	return comm_get_sem(nsems,IPC_CREAT);
}
int init_sem(int sem_id,int which)
{
	union semun _semun;
	_semun.val=1;
	int ret=semctl(sem_id,which,SETVAL,_semun,NULL);
	return ret;
}
static int op_sem(int sem_id,int which,int op)
{
	struct sembuf _sem_buf;
	_sem_buf.sem_num=which;
	_sem_buf.sem_op=op;
	_sem_buf.sem_flg=0;
	return semop(sem_id,&_sem_buf,1);
}
int p_sem_op(int sem_id,int which)
{
	return op_sem(sem_id,which,-1);
}
int v_sem_op(int sem_id,int which)
{
	return op_sem(sem_id,which,+1);
}





static int comm_get_shm(int shm_size,int flag)
{
	key_t shm_key=ftok(_PATH_,_PROJ_ID_);
	if(shm_key<0)
	{
		perror("ftok");
		return -1;
	}
	int shm_id=shmget(shm_key,shm_size,flag);
	if(shm_id<0)
	{
			perror("shmget");
	}
	return shm_id;
}

int creat_shm(int shm_size)
{
	umask(0);
	return comm_get_shm(shm_size,IPC_CREAT|IPC_EXCL|0666);
}
int get_shm()
{
	return comm_get_shm(1,IPC_CREAT);
}

void *at_shm(int shm_id)
{
	return shmat(shm_id,NULL,0);
}
int delete_shm(void *addr)
{
	return shmdt(addr);
}
int distroy_shm(int shm_id)
{
	return shmctl(shm_id,IPC_RMID,NULL);
}











